"""
擎动智造自动化执行平台 - FastAPI主应用
"""
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles

from config import settings
from routers import auth, workstations, websocket


# 创建FastAPI应用
app = FastAPI(
    title="擎动智造自动化执行平台",
    description="基于FastAPI的自动化执行平台后端服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 配置CORS
origins = settings.CORS_ORIGINS.split(",")
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,  # 允许携带Cookie
    allow_methods=["*"],
    allow_headers=["*"],
)


# 注册路由
app.include_router(auth.router, prefix=settings.API_V1_PREFIX)
app.include_router(workstations.router, prefix=settings.API_V1_PREFIX)
app.include_router(websocket.router, prefix=settings.API_V1_PREFIX)


# 配置静态文件服务
# 前端构建文件路径
FRONTEND_DIST_PATH = Path(__file__).parent.parent.parent / "ui" / "dist"

if FRONTEND_DIST_PATH.exists():
    # 挂载静态资源目录
    app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIST_PATH / "assets")), name="assets")
    
    @app.get("/", tags=["前端页面"])
    async def serve_frontend():
        """提供前端页面"""
        index_path = FRONTEND_DIST_PATH / "index.html"
        if index_path.exists():
            return FileResponse(index_path)
        return {
            "message": "擎动智造自动化执行平台 API",
            "version": "1.0.0",
            "docs": "/docs",
            "redoc": "/redoc",
            "note": "前端页面未构建，请运行: cd ui && npm run build"
        }
    
    # 处理前端路由，所有非API路径都返回index.html
    @app.get("/{full_path:path}", tags=["前端页面"])
    async def serve_frontend_routes(full_path: str):
        """处理前端路由"""
        # 如果是API路径，不处理
        if full_path.startswith("api/") or full_path.startswith("docs") or full_path.startswith("redoc") or full_path.startswith("health"):
            return JSONResponse(
                status_code=404,
                content={"detail": "Not Found"}
            )
        
        # 检查是否是静态文件
        file_path = FRONTEND_DIST_PATH / full_path
        if file_path.is_file():
            return FileResponse(file_path)
        
        # 否则返回index.html（前端路由）
        index_path = FRONTEND_DIST_PATH / "index.html"
        if index_path.exists():
            return FileResponse(index_path)
        
        return JSONResponse(
            status_code=404,
            content={"detail": "Not Found"}
        )
else:
    @app.get("/", tags=["根路径"])
    async def root():
        """根路径"""
        return {
            "message": "擎动智造自动化执行平台 API",
            "version": "1.0.0",
            "docs": "/docs",
            "redoc": "/redoc",
            "note": "前端页面未构建，请运行: cd ui && npm run build"
        }


@app.get("/health", tags=["健康检查"])
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "service": "InnoDrive Execution Platform"
    }


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """全局异常处理器"""
    print(f"❌ 全局异常: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": "服务器内部错误",
            "data": None
        }
    )


if __name__ == "__main__":
    import uvicorn
    import webbrowser
    import threading
    import time
    
    # 检查前端是否已构建
    frontend_built = FRONTEND_DIST_PATH.exists()
    
    print("=" * 60)
    print("🚀 擎动智造自动化执行平台 - 后端服务启动中...")
    print(f"📍 服务地址: http://{settings.HOST}:{settings.PORT}")
    print(f"📚 API文档: http://{settings.HOST}:{settings.PORT}/docs")
    print(f"🔐 认证方式: JWT (RS256)")
    
    if frontend_built:
        print(f"🌐 前端页面: http://localhost:{settings.PORT}")
    else:
        print("⚠️  前端未构建，请运行: cd ui && npm run build")
    
    print("=" * 60)
    
    # 自动打开浏览器
    def open_browser():
        """延迟打开浏览器"""
        time.sleep(2)  # 等待服务启动
        url = f"http://localhost:{settings.PORT}"
        print(f"\n🌐 正在打开浏览器: {url}\n")
        try:
            webbrowser.open(url)
        except Exception as e:
            print(f"⚠️  无法自动打开浏览器: {e}")
    
    # 在后台线程中打开浏览器
    if frontend_built:
        browser_thread = threading.Thread(target=open_browser, daemon=True)
        browser_thread.start()
    
    # 启动服务
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=False,  # 生产模式不需要热重载
        log_level="info"
    )
